﻿namespace SettingsControl
{
    public static class Settings
    {
        public static void SetValue(string section, string key, string value)
        {
            //categorize储存分段信息，<分段名称, 起始位置, 数据行数>
            List<Tuple<string, int, int>> categorize = [];
            //data储存所有数据行
            List<string> data = [];

            string sSec = "[" + section + "]";

            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Settings.ini";
            if (File.Exists(filepath))
            {
                string[]? lines = File.ReadAllLines(filepath);
                foreach (string line in lines)
                {
                    if(!string.IsNullOrEmpty(line))
                    {
                        if (line[0] == '[' && line[line.Length - 1] == ']')
                            data.Add(line);
                        if (line.Contains('='))
                            data.Add(line);
                    }
                }

                //根据data获取分段信息
                if (data.Count != 0)
                {
                    int sPos = -1, sLen = 0;
                    string cat = "", sRead;
                    for (int i = 0; i < data.Count; i++)
                    {
                        sRead = data[i];
                        if (sRead[0] == '[' && sRead[sRead.Length - 1] == ']')
                        {
                            if (sPos != -1 && cat != "")
                            {
                                Tuple<string, int, int> t = new(cat, sPos, sLen);
                                categorize.Add(t);
                                cat = "";
                            }
                            sPos = i;
                            sLen = 0;
                            cat = sRead;
                        }
                        else
                        {
                            if (sPos != -1)
                                sLen++;
                        }
                        if (i == data.Count - 1 && sPos != -1 && cat != "")
                        {
                            Tuple<string, int, int> t = new(cat, sPos, sLen);
                            categorize.Add(t);
                            cat = "";
                        }
                    }
                }

                //判断要设置的数据的段名和键名是否存在
                if (categorize.Count != 0)
                {
                    bool findSec = false, findVal = false;
                    int secPos = -1;
                    for (int i = 0; i < categorize.Count; i++)
                    {
                        if (categorize[i].Item1 == sSec)
                        {
                            findSec = true;
                            secPos = i;
                            for (int j = 1; j < categorize[i].Item3 + 1; j++)
                            {
                                string tKey = data[categorize[i].Item2 + j];
                                tKey = tKey.Substring(0, tKey.IndexOf('='));
                                //当段名和键名都存在，如果数据不同就修改数据，数据相同就直接退出不修改配置文件
                                if (tKey == key)
                                {
                                    findVal = true;
                                    if (data[categorize[i].Item2 + j] != key + "=" + value)
                                    {
                                        data[categorize[i].Item2 + j] = key + "=" + value;
                                    }
                                    else
                                        return;
                                }
                            }
                        }
                    }

                    //段名不存在时，新建段名和键名
                    if (!findSec)
                    {
                        data.Add(sSec);
                        data.Add(key + "=" + value);
                    }
                    //段名存在但键名不存在时，在段末新建键名
                    if (findSec && !findVal)
                    {
                        string vs = key + "=" + value;
                        int iPos = categorize[secPos].Item2 + categorize[secPos].Item3 + 1;
                        data.Insert(iPos, vs);
                    }
                }
            }
            else
            {
                //当配置文件不存在时新建数据
                data.Add(sSec);
                data.Add(key + "=" + value);
            }

            //写入前用空行分段提高可读性
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i][0] == '[' && data[i][data[i].Length - 1] == ']' && i != 0)
                {
                    data.Insert(i, "");
                    i++;
                }
            }

            File.WriteAllLines(filepath, data);
        }

        public static string GetValue(string section, string key)
        {
            //分段section、键名key转换为string
            string sSec = "[" + section + "]";
            //载入数据，找到分段后在分段内寻找数据，超出分段或文件尾即未找到
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Settings.ini";
            bool findSec = false;
            if (File.Exists(filepath))
            {
                string[]? lines = File.ReadAllLines(filepath);
                foreach (string line in lines)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        if (findSec)
                        {
                            if (line[0] == '[' && line[line.Length - 1] == ']')
                                return string.Empty;
                            int tPos = line.IndexOf('=');
                            if (tPos > 0)
                            {
                                string tKey = line.Substring(0, tPos);
                                if (tKey == key)
                                {
                                    if (line.Length > tPos + 1)
                                    {
                                        string tVal = line.Substring(tPos + 1, line.Length - tPos - 1);
                                        return tVal;
                                    }
                                    else
                                        return string.Empty;
                                }
                            }
                            else
                                return string.Empty;
                        }
                        if (line == sSec)
                        {
                            findSec = true;
                        }
                    }
                }
            }
            return string.Empty;
        }
    }
}
